﻿using ApiCommon;
using Dillon.Security;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http;
using System.Xml;

namespace WeiXinMongoApis.Controllers
{
    public class AuthorizationController : ApiController
    {
        /// <summary>
        /// 试用天数
        /// </summary>
        int PreviewDay = int.Parse(ConfigurationManager.AppSettings["previewDay"].ToString());

        /// <summary>
        /// 试用者名单文件名
        /// </summary>
        const string TrialUsersFileName = "TrialUsers.txt";

        // GET api/values/5
        public ValueResult Get(string clientId)
        {
            //是否需要加入试用者名单
            bool needToAppendTrialList = true;

            using (FileStream file = new FileStream(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, TrialUsersFileName), FileMode.OpenOrCreate))
            {
                StreamReader sr = new StreamReader(file);
                String line;

                while ((line = sr.ReadLine()) != null)
                {
                    string[] cols = line.Split(',');
                    if (cols[0] == clientId)
                    {
                        needToAppendTrialList = false;
                        if (DateTime.Parse(cols[1]).AddDays(PreviewDay) < DateTime.Now)
                        {
                            throw new ApiException(1, "对不起，您的试用期限已过，请联系开发商购买。");
                        }
                    }
                }
            }

            //生成授权码
            string authorizationCode = this.GetAuthorizationInfo(clientId);

            if (needToAppendTrialList)
            {
                using (FileStream file = new FileStream(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, TrialUsersFileName), FileMode.Append))
                {
                    //加入试用者名单
                    StreamWriter sw = new StreamWriter(file);
                    StringBuilder sb = new StringBuilder();
                    string[] data = { clientId, DateTime.Now.ToString("yyyy-MM-dd") };
                    sw.WriteLine(string.Join(",", data.ToArray()),true);
                    sw.Close();
                }
            }

            return new ValueResult()
            {
                Values = new string[] { authorizationCode }
            };
        }

        private string GetAuthorizationInfo(string clientIdentity)
        {
            string privateKey;
            //获取私钥
            using (FileStream file = new FileStream(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "PrivateKey.log"), FileMode.OpenOrCreate))
            {
                StreamReader sr = new StreamReader(file);
                privateKey = sr.ReadToEnd();
            }

            System.Security.Cryptography.RSACryptoServiceProvider p = new System.Security.Cryptography.RSACryptoServiceProvider();
            p.FromXmlString(privateKey);
            var ep = p.ExportParameters(true);

            var d = Convert.ToBase64String(ep.D);
            var n = Convert.ToBase64String(ep.Modulus);
            return RC2RSA.Encrypt(this.GetClientAuthorization(clientIdentity, DateTime.Now, DateTime.Now.AddDays(PreviewDay)), d, n);
        }

        private string GetClientAuthorization(string clientIdentity, DateTime fromDate, DateTime toDate)
        {

            StringBuilder authorizationBuilder = new StringBuilder();
            authorizationBuilder.AppendFormat("ClientIdentity:{0}", clientIdentity).AppendLine();
            authorizationBuilder.AppendFormat("FromDate:{0}", fromDate.ToString("yyyy/MM/dd")).AppendLine();
            authorizationBuilder.AppendFormat("ToDate:{0}", toDate.ToString("yyyy/MM/dd")).AppendLine();
            return authorizationBuilder.ToString();
        }
    }   
}
